package com.hehui.module.customer.controller;

import com.hehui.common.core.commom.AjaxResult;
import com.hehui.common.core.controller.BaseController;
import com.hehui.common.core.page.TableDataInfo;
import com.hehui.common.utils.SecurityUtils;
import com.hehui.common.utils.StringUtils;
import com.hehui.module.customer.entity.BaseCustomer;
import com.hehui.module.customer.service.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;



/*  待修改
SELECT
	bc_customerId,
	bc_merchantId,
	'客户编号',
	'bc_typeId',
	'业务员',
	'辅业务员',
	bc_clearing,
	bc_name,
	bc_mobile,
	bc_state,
	remarks
FROM
	base_customer
WHERE
	bc_merchantId = 1
	AND is_del= '0';
 */


@RestController
@RequestMapping("/customer")
public class CustomerController extends BaseController {

    @Autowired
    private ICustomerService customerService;

    /*分页查询客户列表*/
    @GetMapping("/list")
    public TableDataInfo customerlist(BaseCustomer baseCustomer) {
        startPage();
        List<BaseCustomer> list = customerService.selectCustomerList(baseCustomer);
        return getDataTable(list);
    }

    /**根据客户ID  查询客户信息*/
    @GetMapping(value = {"/", "/{customerId}"})
    public AjaxResult getCustomerInfoById(@PathVariable(value = "customerId", required = false) Long customerId) {
        AjaxResult ajax = AjaxResult.success();
        BaseCustomer customer = new BaseCustomer();
        customer = customerService.selectByPrimaryKey(customerId);
        ajax.put("customer", customer);
        return ajax;
    }

    /**添加用户 管理端不用此接口   仅用于测试*/
    @PostMapping("/add")
    public AjaxResult addCustomer(@Validated @RequestBody BaseCustomer baseCustomer) {
        System.out.println(baseCustomer.getTrademarks()+"****");
        // 用户名是否存在
        if (StringUtils.isNotEmpty(baseCustomer.getUsername()) && customerService.checkUserNameUnique(baseCustomer.getUsername(), baseCustomer.getMerchantId()) == false) {
            return AjaxResult.error("添加'" + baseCustomer.getUsername() + "'失败，用户名已存在");
            //手机号是否存在
        }
        if (StringUtils.isNotEmpty(baseCustomer.getMobile()) && customerService.checkMobileUnique(baseCustomer.getMobile(), baseCustomer.getMerchantId()) == false) {
            return AjaxResult.error("添加'" + baseCustomer.getMobile() + "'失败，手机号已存在");
            // 邮箱是否存在
        }
        if (StringUtils.isNotEmpty(baseCustomer.getMail()) && customerService.checkMailUnique(baseCustomer.getMail(), baseCustomer.getMerchantId()) == false) {
            return AjaxResult.error("添加'" + baseCustomer.getMail() + "'失败，邮箱已存在");
        }
        // 编号是否存在
        if (StringUtils.isNotEmpty(baseCustomer.getNum()) && customerService.checkNumUnique(baseCustomer.getNum(), baseCustomer.getMerchantId()) == false) {
            return AjaxResult.error("添加'" + baseCustomer.getNum() + "'失败，编号已存在");
        }

        baseCustomer.setPassword(SecurityUtils.encryptPassword(baseCustomer.getPassword()));
        baseCustomer.setCreateTime(new Date());
        baseCustomer.setUpdateTime(new Date());
        baseCustomer.setClearing("3");
        baseCustomer.setIsDel("0");
        baseCustomer.setRegister("1");
        return toAjax(customerService.insertCustomer(baseCustomer));
    }

    /*修改用户信息 */
    @PutMapping("/update")
    public AjaxResult updateCustomer(@Validated @RequestBody BaseCustomer baseCustomer) {
        BaseCustomer old = customerService.selectByPrimaryKey(baseCustomer.getCustomerId());
        if (old == null) {
            return AjaxResult.error("客户不存在");
        }
        //判断手机号和邮箱
        if (StringUtils.isNotEmpty(baseCustomer.getMobile())) {
            if (!old.getMobile().equals(baseCustomer.getMobile())) {
                if (customerService.checkMobileUnique(baseCustomer.getMobile(), baseCustomer.getMerchantId()) == false) {
                    return AjaxResult.error("修改失败，手机号已存在");
                }
            }
        }
        if (StringUtils.isNotEmpty(baseCustomer.getMobile())) {
            if (!old.getMail().equals(baseCustomer.getMail())) {
                if (customerService.checkMailUnique(baseCustomer.getMail(), baseCustomer.getMerchantId()) == false) {
                    return AjaxResult.error("修改失败，邮箱已存在");
                }
            }
        }

        if (StringUtils.isNotEmpty(baseCustomer.getNum())) {
            if (!old.getNum().equals(baseCustomer.getNum())) {
                if (customerService.checkNumUnique(baseCustomer.getNum(), baseCustomer.getMerchantId()) == false) {
                    return AjaxResult.error("修改失败，编号已存在");
                }
            }
        }
        if (StringUtils.isNotEmpty(baseCustomer.getPassword())) {
            baseCustomer.setPassword(SecurityUtils.encryptPassword(baseCustomer.getPassword()));
        }
        baseCustomer.setUpdateTime(new Date());
        return toAjax(customerService.updateCustomer(baseCustomer));

    }
    /* 1待审核 2待激活 3已启用 4已停用
     *批量修改状态
     */

    @PutMapping(value = {"/", "/{customerIds}/{state}"})
    public AjaxResult updateCustomerStateByIds(@PathVariable(value = "customerIds", required = false) Long[] customerIds, @PathVariable(value = "state", required = false) String state) {
        return toAjax(customerService.updateCustomerStateByIds(customerIds, state));
    }

    //校验用户名
    public AjaxResult checkUserNameUnique(String username) {
        Long merchantId = SecurityUtils.getMerchantId();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("result", true);
        if (customerService.checkUserNameUnique(username, merchantId) == false) {
            ajax.put("result", false);
        }
        return ajax;
    }

    //校验手机号
    public AjaxResult checkMobileUnique(String mobile) {
        Long merchantId = SecurityUtils.getMerchantId();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("result", true);
        if (customerService.checkMobileUnique(mobile, merchantId) == false) {
            ajax.put("result", false);
        }
        return ajax;
    }

    //校验邮箱
    public AjaxResult checkMailUnique(String mail) {
        Long merchantId = SecurityUtils.getMerchantId();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("result", true);
        if (customerService.checkMailUnique(mail, merchantId) == false) {
            ajax.put("result", false);
        }
        return ajax;
    }

    //逻辑删除客户 修改状态为删除状态
    @DeleteMapping(value = {"/", "/{customerIds}"})
    public AjaxResult updateCustomerStateByIds(@PathVariable(value = "customerIds", required = false) Long[] customerIds) {
        return toAjax(customerService.deleteCustomerByIds(customerIds));
    }

    //获取编号
    @GetMapping("/getnum")
    public AjaxResult createCustomerNum() {
        return AjaxResult.success("成功",customerService.createNewNum(SecurityUtils.getMerchantId()));
    }
}
